home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / orca / espeechfactory.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  16.6 KB  |  470 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Python wrapper for Emacspeak speech servers.
  5.  
  6. The emacspeak TTS server provides a simple but powerful and
  7. well-tested speech-server abstraction. That server is implemented
  8. as an external program (typically in TCL).  This wrapper class
  9. provides Python access to available Emacspeak speech servers.
  10.  
  11. Initially, this class will provide Python access to the TTS
  12. server commands.  Over time, this module may also implement
  13. functionality present in Emacspeak's Lisp layer ---specifically,
  14. higher level TTS functionality provided by the following
  15. emacspeak modules:
  16.  
  17. 0)  dtk-speak.el
  18.  
  19. 1)  emacspeak-pronounce.el
  20.  
  21. 2)  accs-structure.el
  22.  
  23. """
  24. __id__ = '$Id: espeechfactory.py 4456 2009-01-22 15:10:40Z wwalker $'
  25. __author__ = 'T. V. Raman'
  26. __version__ = '$Revision: 4456 $'
  27. __date__ = '$Date: 2009-01-22 10:10:40 -0500 (Thu, 22 Jan 2009) $'
  28. __copyright__ = 'Copyright (c) 2005-2008 Google Inc.'
  29. __license__ = 'LGPL'
  30. __all__ = [
  31.     'Speaker']
  32. import os
  33. import re
  34. import debug
  35. import settings
  36. import speechserver
  37. from orca_i18n import _
  38.  
  39. class SpeechServer(speechserver.SpeechServer):
  40.     '''Provides speech server abstraction.
  41.  
  42.     Class Variables:
  43.  
  44.         location -- specifies directory where Emacspeak
  45.         speech servers are installed.
  46.  
  47.         config --  dictionary of default settings.
  48.  
  49.     Speaker objects can be initialized with the following parameters:
  50.  
  51.         engine -- TTS server to instantiate. Default: outloud
  52.         host -- Host that runs   server. Default: localhost
  53.         settings -- Dictionary of default settings.
  54.  
  55.     '''
  56.     location = '/usr/share/emacs/site-lisp/emacspeak/servers'
  57.     config = {
  58.         'splitcaps': 1,
  59.         'rate': 70,
  60.         'capitalize': 0,
  61.         'allcaps': 0,
  62.         'punctuations': 'all' }
  63.     __activeServers = { }
  64.     _speechChunkRegexp = '.{0,120}?[\n,.;:!?)][]}"]?\\s+|.{1,120}(?:\\Z|\\s+)|.{1,120}'
  65.     
  66.     def getFactoryName():
  67.         '''Returns a localized name describing this factory.'''
  68.         return _('Emacspeak Speech Services')
  69.  
  70.     getFactoryName = staticmethod(getFactoryName)
  71.     
  72.     def getSpeechServers():
  73.         '''Gets available speech servers as a list.  The caller
  74.         is responsible for calling the shutdown() method of each
  75.         speech server returned.
  76.         '''
  77.         haveNewServers = False
  78.         serversConf = file(os.path.join(SpeechServer.location, '.servers'))
  79.         for name in serversConf:
  80.             name = name.strip()
  81.             if name == '' or name[0] == '#':
  82.                 continue
  83.             
  84.             if name not in SpeechServer._SpeechServer__activeServers:
  85.                 
  86.                 try:
  87.                     SpeechServer._SpeechServer__activeServers[name] = SpeechServer(name)
  88.                     haveNewServers = True
  89.                 debug.printException(debug.LEVEL_WARNING)
  90.  
  91.                 continue
  92.         
  93.         serversConf.close()
  94.         if haveNewServers:
  95.             sleep = sleep
  96.             import time
  97.             sleep(1)
  98.         
  99.         for server in SpeechServer._SpeechServer__activeServers.values():
  100.             if not (server.process) or server.process.poll() is not None:
  101.                 server.shutdown()
  102.                 continue
  103.         
  104.         return SpeechServer._SpeechServer__activeServers.values()
  105.  
  106.     getSpeechServers = staticmethod(getSpeechServers)
  107.     
  108.     def getSpeechServer(info = [
  109.         'outloud',
  110.         'outloud']):
  111.         '''Gets a given SpeechServer based upon the info.
  112.         See SpeechServer.getInfo() for more info.
  113.         '''
  114.         if info[0] in SpeechServer._SpeechServer__activeServers:
  115.             return SpeechServer._SpeechServer__activeServers[info[0]]
  116.         
  117.         try:
  118.             return SpeechServer(info[0])
  119.         except:
  120.             info[0] in SpeechServer._SpeechServer__activeServers
  121.             debug.printException(debug.LEVEL_SEVERE)
  122.  
  123.         return None
  124.  
  125.     getSpeechServer = staticmethod(getSpeechServer)
  126.     
  127.     def shutdownActiveServers():
  128.         '''Cleans up and shuts down this factory.
  129.         '''
  130.         for server in SpeechServer._SpeechServer__activeServers.values():
  131.             server.shutdown()
  132.         
  133.  
  134.     shutdownActiveServers = staticmethod(shutdownActiveServers)
  135.     
  136.     def __init__(self, engine = 'outloud', host = 'localhost', initial = config):
  137.         '''Launches speech engine.'''
  138.         speechserver.SpeechServer.__init__(self)
  139.         self._engine = engine
  140.         self._output = None
  141.         self.process = None
  142.         e = __import__(_getcodes(engine), globals(), locals(), [
  143.             ''])
  144.         self.getvoice = e.getvoice
  145.         self.getrate = e.getrate
  146.         self.getvoicelist = e.getvoicelist
  147.         self._specialChars = e.makeSpecialCharMap()
  148.         if host == 'localhost':
  149.             self._server = os.path.join(SpeechServer.location, self._engine)
  150.         else:
  151.             self._server = os.path.join(SpeechServer.location, 'ssh-%s' % self._engine)
  152.         Popen = Popen
  153.         PIPE = PIPE
  154.         import subprocess
  155.         proc = Popen(self._server, close_fds = True, stdin = PIPE, stdout = PIPE, stderr = PIPE)
  156.         proc.stdout.close()
  157.         proc.stderr.close()
  158.         proc.stdout = None
  159.         proc.stderr = None
  160.         self._output = proc.stdin
  161.         self.process = proc
  162.         self._speechChunk = re.compile(self._speechChunkRegexp, re.DOTALL)
  163.         self._settings = { }
  164.         if initial:
  165.             self._settings.update(initial)
  166.             self.configure(self._settings)
  167.         
  168.  
  169.     
  170.     def configure(self, engineSettings):
  171.         '''Configure engine with settings.'''
  172.         for k in engineSettings.keys():
  173.             if hasattr(self, k) and callable(getattr(self, k)):
  174.                 getattr(self, k)(engineSettings[k])
  175.                 continue
  176.         
  177.  
  178.     
  179.     def settings(self):
  180.         return self._settings
  181.  
  182.     
  183.     def getInfo(self):
  184.         '''Returns [driverName, serverId]
  185.         '''
  186.         return [
  187.             self._engine,
  188.             self._engine]
  189.  
  190.     
  191.     def getVoiceFamilies(self):
  192.         '''Returns a list of speechserver.VoiceFamily instances
  193.         representing all the voice families known by the speech server.
  194.         '''
  195.         families = []
  196.         
  197.         try:
  198.             for voice in self.getvoicelist():
  199.                 props = {
  200.                     speechserver.VoiceFamily.NAME: voice }
  201.                 families.append(speechserver.VoiceFamily(props))
  202.         except:
  203.             debug.printException(debug.LEVEL_SEVERE)
  204.  
  205.         return families
  206.  
  207.     
  208.     def _quoteSpecialChars(self, text):
  209.         '''Replaces all special characters in text by their replacements
  210.         according to self._specialChars.
  211.         '''
  212.         for char, name in self._specialChars:
  213.             text = text.replace(char, name)
  214.         
  215.         return text
  216.  
  217.     
  218.     def queueText(self, text = '', acss = None):
  219.         '''Adds the text to the queue.
  220.  
  221.         Arguments:
  222.         - text: text to be spoken
  223.         - acss: acss.ACSS instance; if None,
  224.                 the default voice settings will be used.
  225.                 Otherwise, the acss settings will be
  226.                 used to augment/override the default
  227.                 voice settings.
  228.  
  229.         Output is produced by the next call to speak.
  230.         '''
  231.         if not settings.enableSpeech:
  232.             return None
  233.         cmd = 'q { %s }\n'
  234.         for chunk in (lambda .0: for t in .0:
  235. t.group())(self._speechChunk.finditer(text)):
  236.             self._output.write(cmd % self._quoteSpecialChars(chunk))
  237.         
  238.  
  239.     
  240.     def queueTone(self, pitch = 440, duration = 50):
  241.         '''Adds a tone to the queue.
  242.  
  243.         Output is produced by the next call to speak.
  244.         '''
  245.         self._output.write('t %s %s\n ' % (pitch, duration))
  246.  
  247.     
  248.     def queueSilence(self, duration = 50):
  249.         '''Adds silence to the queue.
  250.  
  251.         Output is produced by the next call to speak.
  252.         '''
  253.         self._output.write('sh  %s' % duration)
  254.  
  255.     
  256.     def speakCharacter(self, character, acss = None):
  257.         '''Speaks a single character immediately.
  258.  
  259.         Arguments:
  260.         - character: text to be spoken
  261.         - acss:      acss.ACSS instance; if None,
  262.                      the default voice settings will be used.
  263.                      Otherwise, the acss settings will be
  264.                      used to augment/override the default
  265.                      voice settings.
  266.         '''
  267.         if character in '{\\}':
  268.             character = self._quoteSpecialChars(character)
  269.         
  270.         self._output.write('l {%s}\n' % character)
  271.         self._output.flush()
  272.  
  273.     
  274.     def speakUtterances(self, utteranceList, acss = None, interrupt = True):
  275.         '''Speaks the given list of utterances immediately.
  276.  
  277.         Arguments:
  278.         - utteranceList: list of strings to be spoken
  279.         - acss:      acss.ACSS instance; if None,
  280.                      the default voice settings will be used.
  281.                      Otherwise, the acss settings will be
  282.                      used to augment/override the default
  283.                      voice settings.
  284.         - interrupt: if True, stop any speech currently in progress.
  285.         '''
  286.         for utt in utteranceList:
  287.             self.queueText(str(utt), acss)
  288.         
  289.         self._output.write('d\n')
  290.         self._output.flush()
  291.  
  292.     
  293.     def speak(self, text = '', acss = None, interrupt = True):
  294.         '''Speaks all queued text immediately.  If text is not None,
  295.         it is added to the queue before speaking.
  296.  
  297.         Arguments:
  298.         - text:      optional text to add to the queue before speaking
  299.         - acss:      acss.ACSS instance; if None,
  300.                      the default voice settings will be used.
  301.                      Otherwise, the acss settings will be
  302.                      used to augment/override the default
  303.                      voice settings.
  304.         - interrupt: if True, stops any speech in progress before
  305.                      speaking the text
  306.         '''
  307.         if not settings.enableSpeech:
  308.             return None
  309.         self.queueText(text, acss)
  310.         self._output.write('d\n')
  311.         self._output.flush()
  312.  
  313.     
  314.     def increaseSpeechPitch(self, step = 0.5):
  315.         '''Increases the speech pitch.'''
  316.         self._settings['average-pitch'] += step
  317.  
  318.     
  319.     def decreaseSpeechPitch(self, step = 0.5):
  320.         '''Decreases the speech pitch.'''
  321.         self._settings['average-pitch'] -= step
  322.  
  323.     
  324.     def increaseSpeechRate(self, step = 5):
  325.         '''Increases the speech rate.
  326.         '''
  327.         self._settings['rate'] += step
  328.         self._output.write('tts_set_speech_rate %s\n' % self.getrate(self._settings['rate']))
  329.         self._output.flush()
  330.  
  331.     
  332.     def decreaseSpeechRate(self, step = 5):
  333.         '''Decreases the speech rate.
  334.         '''
  335.         self._settings['rate'] -= step
  336.         self._output.write('tts_set_speech_rate %s\n' % self.getrate(self._settings['rate']))
  337.         self._output.flush()
  338.  
  339.     
  340.     def stop(self):
  341.         '''Stops ongoing speech and flushes the queue.'''
  342.         self._output.write('s\n')
  343.         self._output.flush()
  344.  
  345.     
  346.     def shutdown(self):
  347.         '''Shuts down the speech engine.'''
  348.         if self.process is None:
  349.             return None
  350.         if self.process.poll() is None:
  351.             SIGKILL = SIGKILL
  352.             import signal
  353.             os.kill(self.process.pid, SIGKILL)
  354.             self.process.wait()
  355.         
  356.         self._output.close()
  357.         self._output = None
  358.         self.process = None
  359.         if self is SpeechServer._SpeechServer__activeServers.get(self._engine, None):
  360.             del SpeechServer._SpeechServer__activeServers[self._engine]
  361.         
  362.  
  363.     
  364.     def reset(self, text = None, acss = None):
  365.         '''Resets the speech engine.'''
  366.         self._output.write('tts_reset\n')
  367.         self._output.flush()
  368.  
  369.     
  370.     def version(self):
  371.         '''Speak TTS version info.'''
  372.         self._output.write('version\n')
  373.  
  374.     
  375.     def punctuations(self, mode):
  376.         '''Set punctuation mode.'''
  377.         if mode in ('all', 'some', 'none'):
  378.             self._settings['punctuations'] = mode
  379.             self._output.write('tts_set_punctuations %s\n' % mode)
  380.             self._output.flush()
  381.         
  382.  
  383.     
  384.     def rate(self, r):
  385.         '''Set speech rate.'''
  386.         self._settings['rate'] = r
  387.         self._output.write('tts_set_speech_rate %s\n' % self.getrate(r))
  388.         self._output.flush()
  389.  
  390.     
  391.     def splitcaps(self, flag):
  392.         '''Set splitcaps mode. 1  turns on, 0 turns off'''
  393.         if not bool(flag) or 1:
  394.             pass
  395.         flag = 0
  396.         self._settings['splitcaps'] = flag
  397.         self._output.write('tts_split_caps %s\n' % flag)
  398.         self._output.flush()
  399.  
  400.     
  401.     def capitalize(self, flag):
  402.         '''Set capitalization  mode. 1  turns on, 0 turns off'''
  403.         if not bool(flag) or 1:
  404.             pass
  405.         flag = 0
  406.         self._settings['capitalize'] = flag
  407.         self._output.write('tts_capitalize %s\n' % flag)
  408.         self._output.flush()
  409.  
  410.     
  411.     def allcaps(self, flag):
  412.         '''Set allcaps  mode. 1  turns on, 0 turns off'''
  413.         if not bool(flag) or 1:
  414.             pass
  415.         flag = 0
  416.         self._settings['allcaps'] = flag
  417.         self._output.write('tts_allcaps_beep %s\n' % flag)
  418.         self._output.flush()
  419.  
  420.     
  421.     def __del__(self):
  422.         '''Shuts down the speech engine.'''
  423.         self.shutdown()
  424.  
  425.  
  426.  
  427. def _getcodes(engine):
  428.     '''Helper function that fetches synthesizer codes for a
  429.     specified engine.'''
  430.     if engine not in _codeTable:
  431.         raise Exception('No code table for %s' % engine)
  432.     engine not in _codeTable
  433.     return _codeTable[engine]
  434.  
  435. _codeTable = {
  436.     'dtk-exp': 'dectalk',
  437.     'dtk-mv': 'dectalk',
  438.     'dtk-soft': 'dectalk',
  439.     'outloud': 'outloud' }
  440.  
  441. def _test():
  442.     '''Self test.'''
  443.     import time
  444.     import acss
  445.     s = SpeechServer()
  446.     a = acss.ACSS()
  447.     s.punctuations('some')
  448.     s.queueText('This is an initial test.')
  449.     s.queueText("Next, we'll test audio formatted output.")
  450.     for d in [
  451.         'average-pitch',
  452.         'pitch-range',
  453.         'richness',
  454.         'stress']:
  455.         for i in range(0, 10, 2):
  456.             a[d] = i
  457.             s.queueText('Set %s to %i. ' % (d, i), a)
  458.         
  459.         del a[d]
  460.         s.queueText('Reset %s.' % d, a)
  461.     
  462.     s.speak()
  463.     print 'sleeping  while waiting for speech to complete.'
  464.     time.sleep(40)
  465.     s.shutdown()
  466.  
  467. if __name__ == '__main__':
  468.     _test()
  469.  
  470.